package cn.xh.huiminpay.message;

import cn.xh.huiminpay.model.OrderExt;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import org.apache.rocketmq.spring.core.RocketMQTemplate;

import javax.annotation.Resource;

/**
 * @Auther:Tao
 * @Date: 2022/3/14 17:23
 * @Desc:
 */
@Component
public class ProducerSamle {


    /**
     /* 发送同步消息
     /* @param topic 标题
     /* @param msg  发送信息
     */

//    @Autowired
    @Resource
    RocketMQTemplate rocketMqTemplate;
    public void sendSyncMsg(String topic, String msg){
        rocketMqTemplate.syncSend(topic, msg);
    }


    /**
     \* 发送异步消息
     \* @param topic
     \* @param msg
     */
    public void sendASyncMsg(String topic, String msg){
        rocketMqTemplate.asyncSend(topic, msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println(sendResult.getSendStatus());
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        });
    }

    /**
     \* 消息内容为json格式
     */
    public void sendMsgByJson(String topic, OrderExt orderExt ){
        rocketMqTemplate.syncSend(topic, orderExt);

    }

    /**
     \* 发送延迟消息
     \* 消息内容为json格式
     */
    public void sendMsgByJsonDelay(String topic, OrderExt orderExt){
        //发送同步消息，消息内容将orderExt转为json
        Message<OrderExt> message = MessageBuilder.withPayload(orderExt).build();
        //指定发送超时时间（毫秒）和延迟等级
        rocketMqTemplate.syncSend(topic,message,1000,3);
    }
}
